<template>
	<div>
		<el-tabs v-model="activeTag" class="market-tabs" @tab-click="handleTab">
			<el-tab-pane v-for="item in tags" :key="item.name" :label="item.label" :name="item.name"> </el-tab-pane>
			<ProTable
				ref="proTable"
				:key="tags[activeTag].name"
				:title="tags[activeTag].name"
				:columns="tags[activeTag].columns"
				:requestApi="getTableList"
				:init-param="initParam"
			>
				<template #searchHeader>
					<div class="mb16" v-show="activeTag == '0'">
						<el-button class="mb0" type="primary" v-auth="'baijiu-cert:market:sell:rule:config:invoke'" @click="openRule()"> 集市规则配置 </el-button>
					</div>
				</template>
				<!-- 表格 功能 按钮 -->
				<template #otherButton>
					<el-button v-if="activeTag == '0'" @click="onExport" v-auth="'baijiu-cert:market:sell:export:invoke'"> 导出 </el-button>
					<el-button v-else @click="onExport" v-auth="'baijiu-cert:market:want:export:invoke'"> 导出 </el-button>
				</template>
				<!-- Expand -->
				<template #expand="scope">
					{{ scope.row }}
				</template>

				<!-- 表格操作 -->
				<template #operation="{ row }">
					<el-button type="primary" link v-auth="'baijiu-cert:market:sell:deactivate:invoke'" @click="changeStatus(row.id)"> 强制下架 </el-button>
				</template>
			</ProTable>
		</el-tabs>

		<RuleSetting :visible="ruleVisible" @handleClose="closeRule"></RuleSetting>
	</div>
</template>

<script setup lang="tsx" name="liquorCerMarket">
import { onMounted, ref, reactive, computed, nextTick } from 'vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchMarketSellList, fetchMarketWantList, fetchMarketSellExport, fetchMarketWantExport, fetchMarketStatus } from '/@/api/liquorCer';
import RuleSetting from './dialog/ruleSetting.vue';
import { useDownload } from '/@/hooks/useDownload';
import constant from '/@/utils/constant';
import { render } from 'nprogress';
import { fenToYuan } from '/@/utils/commonFunction';

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'ID',
	paramTimeType: 'publish',
});

const activeTag = ref<any>('0');
const tags = ref<any>([
	{
		label: '出售酒藏',
		name: '0',
		columns: [
			{
				prop: 'keywords',
				label: '商品搜索',
				isShow: false,
				search: {
					span: 2,
					xs: 1,
					sm: 1,
					md: 2,
					lg: 1,
					xl: 1,
					render: (scope: any) => {
						const slot = {
							prepend: () => (
								<el-select
									v-model={scope.searchParam.searchType}
									placeholder="Select"
									style="width: 100px"
									onChange={(value: any) => (scope.searchParam.searchType = value)}
								>
									{searchArr.map((item) => (
										<el-option key={item.value} label={item.label} value={item.value} />
									))}
								</el-select>
							),
						};
						return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
					},
				},
			},
			{
				prop: 'paramTime',
				label: '时间筛选',
				isShow: false,
				search: {
					span: 2,
					xs: 1,
					sm: 1,
					md: 2,
					lg: 1,
					xl: 1,
					render: (scope: any) => {
						return (
							<div class="flex-center">
								<el-select
									v-model={scope.searchParam.paramTimeType}
									placeholder="Select"
									style="width: 100px"
									class="mini-gray-select flex-shrink"
									onChange={(value: any) => (scope.searchParam.paramTimeType = value)}
								>
									{[
										{
											label: '发布时间',
											value: 'publish',
										},
									].map((item) => (
										<el-option key={item.value} label={item.label} value={item.value} />
									))}
								</el-select>
								<el-date-picker
									v-model={scope.searchParam.paramTime}
									type="datetimerange"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									format="YYYY-MM-DD HH:mm:ss"
									date-format="YYYY-MM-DD"
									time-format="HH:mm:ss"
								/>
							</div>
						);
					},
				},
			},
			{
				prop: 'productId',
				label: '商品ID',
				minWidth: 160,
			},
			{
				prop: 'productName',
				label: '商品名称',
				minWidth: 160,
			},
			{
				prop: 'year',
				label: '年份',
				minWidth: 160,
			},
			{
				prop: 'skuId',
				label: '规格ID',
				minWidth: 80,
			},
			{
				prop: 'skuName',
				label: '规格名称',
				minWidth: 160,
			},
			{
				prop: 'restStorageDays',
				label: '剩余存储时长(天)',
				minWidth: 180,
			},
			{
				prop: 'inventory',
				label: '剩余库存',
				minWidth: 180,
			},
			{
				prop: 'price',
				label: '售卖单价(元)',
				minWidth: 180,
				render: (scope: any) => {
					return fenToYuan(scope.row.price);
				},
			},
			{
				prop: 'viewCount',
				label: '浏览次数',
				minWidth: 160,
			},
			{
				prop: 'sellPoint',
				label: '销售卖点',
				minWidth: 180,
			},
			{
				prop: 'publishTime',
				label: '发布时间',
				minWidth: 160,
			},
			{
				prop: 'seller',
				label: '卖家信息',
				minWidth: 240,
				align: 'left',
				render: (scope: any) => {
					return (
						<div class="flex-center">
							<div class="text-primary mr10">{scope.row.seller?.nickname}</div>
							<el-tag type={scope.row.seller?.userType ? 'primary' : 'success'}>{constant.USERTYPE[scope.row.seller?.userType]}</el-tag>
						</div>
					);
				},
			},
			{ prop: 'operation', label: '操作', fixed: 'right', width: 100, align: 'left' },
		],
	},
	{
		label: '求购报价',
		name: '1',
		columns: [
			{
				prop: 'keywords',
				label: '商品搜索',
				isShow: false,
				search: {
					span: 2,
					xs: 1,
					sm: 1,
					md: 2,
					lg: 1,
					xl: 1,
					render: (scope: any) => {
						const slot = {
							prepend: () => (
								<el-select
									v-model={scope.searchParam.searchType}
									placeholder="Select"
									style="width: 100px"
									onChange={(value: any) => (scope.searchParam.searchType = value)}
								>
									{searchArr.map((item) => (
										<el-option key={item.value} label={item.label} value={item.value} />
									))}
								</el-select>
							),
						};
						return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
					},
				},
			},
			{
				prop: 'paramTime',
				label: '时间筛选',
				isShow: false,
				search: {
					span: 2,
					xs: 1,
					sm: 1,
					md: 2,
					lg: 1,
					xl: 1,
					render: (scope: any) => {
						return (
							<div class="flex-center">
								<el-select
									v-model={scope.searchParam.paramTimeType}
									placeholder="Select"
									style="width: 100px"
									class="mini-gray-select flex-shrink"
									onChange={(value: any) => (scope.searchParam.paramTimeType = value)}
								>
									{[
										{
											label: '发布时间',
											value: 'publish',
										},
									].map((item) => (
										<el-option key={item.value} label={item.label} value={item.value} />
									))}
								</el-select>
								<el-date-picker
									v-model={scope.searchParam.paramTime}
									type="datetimerange"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									format="YYYY-MM-DD HH:mm:ss"
									date-format="YYYY-MM-DD"
									time-format="HH:mm:ss"
								/>
							</div>
						);
					},
				},
			},
			{
				prop: 'productId',
				label: '商品ID',
				minWidth: 160,
			},
			{
				prop: 'productName',
				label: '商品名称',
				minWidth: 160,
			},
			{
				prop: 'year',
				label: '年份',
				minWidth: 160,
			},
			{
				prop: 'count',
				label: '求购数量',
				minWidth: 160,
			},
			{
				prop: 'price',
				label: '求购报价',
				minWidth: 180,
			},
			{
				prop: 'buyer',
				label: '买家信息',
				minWidth: 240,
				align: 'left',
				render: (scope: any) => {
					return (
						<div class="flex-center">
							<div class="text-primary mr10">{scope.row.buyer?.nickname}</div>
							<el-tag type={scope.row.buyer?.userType ? 'primary' : 'success'}>{constant.USERTYPE[scope.row.buyer?.userType]}</el-tag>
						</div>
					);
				},
			},
			{
				prop: 'publishTime',
				label: '发布时间',
				minWidth: 160,
			},
		],
	},
]);

const handleParams = (params: any) => {
	let data = {
		...params,
	};
	if (data.paramTime) {
		data.startTime = dayjs(data.paramTime[0]).format('YYYY-MM-DD HH:mm:ss');
		data.endTime = dayjs(data.paramTime[1]).format('YYYY-MM-DD HH:mm:ss');
		delete data.paramTimeType;
		delete data.paramTime;
	}
	return data;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	return (activeTag.value == '0' ? fetchMarketSellList : fetchMarketWantList)(handleParams(params));
};

const searchArr = [
	{
		label: '商品ID',
		value: 'ID',
	},
	{
		label: '商品名称',
		value: 'NAME',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const ruleVisible = ref(false);

const changeStatus = (id: any) => {
	ElMessageBox.confirm('确认下架？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchMarketStatus({ id });
		if (res.code == 200) {
			ElMessage.success('下架成功');
			proTable.value?.getTableList();
		}
	});
};

const handleTab = () => {
	nextTick(() => {
		proTable.value?.getTableList();
	});
};

const openRule = () => {
	ruleVisible.value = true;
};

const closeRule = (success: boolean) => {
	ruleVisible.value = false;

	if (success) {
		proTable.value?.getTableList();
	}
};

// 保存并导出
const onExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(
			activeTag.value == '0' ? fetchMarketSellExport : fetchMarketWantExport,
			activeTag.value == '0' ? '出售酒藏列表' : '求购报价列表',
			handleParams(proTable.value?.searchParam)
		)
	);
};
</script>

<style lang="scss">
.market-tabs {
	.el-tabs__header {
		background-color: #fff;
		position: relative;
		bottom: -25px;
		padding: 0 0 20px;
		border-radius: 20px 20px 0 0;
		margin-bottom: 0px;
	}
}
</style>
